<template>
  <view>
    <scroll-view scroll-y show-scrollbar="false" style="margin-bottom: 120rpx;">
      <view class="content">
        <view class="action">
          <view class="title">
            <view>{{ title }} </view>
            <view> {{ getSpecName }}</view>
          </view>
        </view>

        <view class="time_set">
          <view v-for="(item, index) in classify" :key="index" :class="[active == item.value ? 'active_item' : 'item']"
            @tap="setActive(item.value)">{{ item.name }}</view>
        </view>


        <view class="charts-container">
          <view class="charts-box">
            <chart-panel :chartData="chartData" :categories="categories" :splitNumber="splitNumber" :inScrollView="true"
              :pageScrollTop="pageScrollTop" />
          </view>

        </view>

        <view class="tag-section">
          <view class="tag-row" v-for="(item, index) in specsList" :key="item.spec_id">
            <text class="tag-label">{{ item.spec_name }}</text>
            <view class="tag-list">
              <view v-for="(it, ix) in item.values" :key="it.spec_value_id"
                :class="[specs.find(item => item.spec_value_id == it.spec_value_id) ? 'tag-active' : 'tag']"
                @tap="selectModel(item, it.spec_value_id, it.spec_value)">{{ it.spec_value }}
              </view>
            </view>
          </view>
        </view>
      </view>

      <view class="content price-history">
        <view class="history-header">
          <view class="header-col time">时间</view>
          <view class="header-col price">价格</view>
          <view class="header-col change">涨跌</view>
        </view>

        <view class="history-item" v-for="(item, index) in priceHistory" :key="index">
          <view class="item-col time">{{ item.date }}</view>
          <view class="item-col price" :class="{ 'up': item.change_type == 'inc', 'down': item.change_type == 'dec' }">
            {{ item.price }}
          </view>
          <view class="item-col change" :class="{ 'up': item.change_type == 'inc', 'down': item.change_type == 'dec' }">
            {{ item.change_type == 'inc' ? '+' + item.change_value : '-' + item.change_value }}
          </view>
        </view>

        <view v-if="!priceHistory.length" style="margin-top: 50rpx;">
          <up-empty mode="list" iconSize="50"></up-empty>
        </view>
      </view>

    </scroll-view>

    <view class="btn_wrap">
      <view class="btn">
        <button class="btn_text" open-type="contact" plain="true">联系客服，顺丰揽收回款</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import chartPanel from '@/components/chartPanel/index.vue'
import { onLoad, onPageScroll, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
import { goodsApi } from '@/api/goods'
import { debounce } from 'lodash'
const active = ref(10) // 10天
const title = ref('')
const priceHistory = ref([])
const splitNumber = 7 // 设置y轴分割数
const pageScrollTop = ref(0) // 添加页面滚动距离ref

// 监听页面滚动
onPageScroll((e) => {
  pageScrollTop.value = e.scrollTop
})

//选中的规格
const specs = ref([])
//商品id
const goods_id = ref()



const chartData = ref([])

const categories = ref([])


// 时间分类
const classify = ref([
  {
    name: '10天',
    value: "10"
  },
  {
    name: '30天',
    value: "30"
  },
  {
    name: '60天',
    value: "60"
  },
  {
    name: '180天',
    value: "180"
  }
])

// 规格列表
const specsList = ref([])

// 切换时间
const setActive = (value) => {
  active.value = value
  debounceGetDetailData()
}

// 切换规格
const selectModel = (item, spec_value_id, spec_value) => {
  const index = specs.value.findIndex(fitem => fitem.spec_id == item.spec_id)
  if (index == -1) {
    specs.value.push({ spec_id: item.spec_id, spec_value_id, spec_value })
  } else {
    specs.value[index] = { spec_id: item.spec_id, spec_value_id, spec_value }
  }
  debounceGetDetailData()
}



//根据规格id数组计算规格名称
const getSpecName = computed(() => {
  if (specs.value.length === 0 || specsList.value.length === 0) {
    return ''
  }
  // 直接查找每个 specId 对应的 spec_value
  const names = specs.value.map(spec => {
    for (const item of specsList.value) {
      const value = item.values.find(it => it.spec_value_id == spec.spec_value_id)
      if (value) {
        return value.spec_value
      }
    }
    return '' // 没找到返回空字符串
  })
  return names.join(' ')
})




// 获取详情数据
const getDetailData = async () => {
  //过滤相同的规格
  let uniqueSpecs = []
  if (specs.value.length) {
    uniqueSpecs = specs.value.filter((item, index, self) =>
      index === self.findIndex(t => t.spec_value_id === item.spec_value_id)
    )
  }
  const res = await goodsApi.market({
    goods_id: goods_id.value,
    days: active.value,
    spec: uniqueSpecs
  })
  title.value = res.data.title
  // 如果没有选中规格，则默认选中每个规格的第一个
  // 增加判断，确保API返回了有效的规格数据，避免死循环
  if (specs.value.length === 0 && res.data.specs?.length > 0) {
    specs.value = res.data.specs.map(item => {
      return {
        spec_id: item.spec_id,
        spec_value_id: item.values[0].spec_value_id,
        spec_value: item.values[0].spec_value
      }
    })
    // 再次调用以获取图表和价格历史
    getDetailData()
    return
  }

  // 更新规格列表、图表和价格历史
  specsList.value = res.data.specs
  if (res.data?.chart) {
    categories.value = res.data.chart.dates
    chartData.value = res.data.chart.prices
  }
  if (res.data.price_list) {
    priceHistory.value = res.data.price_list
  }
}

// 防抖后的 getDetailData
const debounceGetDetailData = debounce(getDetailData, 500)

onShareAppMessage(() => {
  return {
    title: '万选回收',
    path: '/pages/subPages/index'
  }
})

onShareTimeline(() => {
  return {
    title: '万选回收',
  }
})

onLoad((options) => {
  const { goodsId, specDetail } = options
  try {
    if (specDetail) {
      specs.value = JSON.parse(specDetail) || []
    }
  } catch (e) {
    console.error('规格参数转换失败:', e, specDetail)
    specs.value = []
  }
  goods_id.value = goodsId
  getDetailData()
})
</script>

<style lang="scss" scoped>
@import '@/index.scss';

.content {
  padding: 24rpx;
  margin: 20rpx;
  box-sizing: border-box;
  background-color: $white;
  border-radius: 16rpx;
}

.action {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}

.title {
  display: flex;
  align-items: center;
  gap: 12rpx;

  &::before {
    content: '';
    display: inline-block;
    width: 12rpx;
    height: 32rpx;
    background: $primary;
    border-radius: 6rpx;
    margin-right: 12rpx;
  }
}

.time_set {
  display: flex;
  margin-top: 40rpx;
  gap: 20rpx;
  justify-content: space-between;
  align-items: center;

  .item,
  .active_item {
    text-align: center;
    font-size: 28rpx;
    color: #666;
    flex: 1;
    padding: 10rpx 0;
    background: #F7F7F7;
    border-radius: 8rpx;
  }

  .active_item {
    color: #fff;
    font-weight: 500;
    background: #E3512B;

  }
}


.charts-container {
  margin: 60rpx 0 80rpx;

  .charts-box {
    height: 450rpx;
    width: 100%;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.tag-section {
  margin-top: 60rpx;

  .tag-row {
    display: flex;
    margin-bottom: 32rpx;
    gap: 40rpx;

    &:last-child {
      margin-bottom: 0;
    }

    .tag-label {
      font-size: 28rpx;
      color: $gray;
      padding: 10rpx 0;
    }

    .tag-list {
      flex: 1;
      display: flex;
      flex-wrap: wrap;


      .tag,
      .tag-active {
        padding: 10rpx 20rpx;
        font-size: 28rpx;
        margin: 0 20rpx 20rpx 0;
        border-radius: 8rpx;
      }

      .tag {
        color: #666;
        background: #f5f5f5;
      }

      .tag-active {
        color: #333;
        background: $light;
      }
    }
  }
}

.divider {
  height: 20rpx;
  background: $main-bg;
}

.price-history {
  .history-header {
    display: flex;
    border-bottom: 1rpx solid #f5f5f5;

    .header-col {
      font-size: 28rpx;
      color: #333;
      text-align: center;
      padding-bottom: 24rpx;

      &.time {
        flex: 2;
        text-align: left;
      }

      &.price,
      &.change {
        flex: 1;
      }
    }
  }

  .history-item {
    display: flex;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f5f5f5;

    &:last-child {
      border-bottom: none;
      padding-bottom: 10rpx;
    }

    .item-col {
      font-size: 24rpx;
      text-align: center;

      &.time {
        flex: 2;
        text-align: left;
        color: #333;
      }

      &.price,
      &.change {
        flex: 1;
      }

      &.up {
        color: $danger;
      }

      &.down {
        color: $green;
      }
    }
  }
}

.btn_wrap {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: $white;
  padding: 20rpx 32rpx 48rpx 32rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

  .btn {
    display: flex;
    align-items: center;
    justify-content: center;
    background: $primary;
    border-radius: 44rpx;
    padding: 20rpx;


    .btn_text {
      font-size: 32rpx;
      color: #fff;
      border: none;
      background: none;
      padding: 0;
      line-height: 1;
    }
  }
}
</style>